/** global jQuery, window document */
/**
 * @todo: try to split js files into different modules
 * @todo: need a assets pipeline, minimize all modules into app.min.js for production use
 */
(function ($, window, document) {

    window.App = window.App || {};
    window.App.Users = {

        url: '/user/ajax',

        /**
         * Init function: run at every js module
         */
        init: function () {
            var that = this;
            var $jqxContainer = $('.jqx-widget-container');
            var $eventListener = $(document);

            $('#show').on('click', function () {
                $.ajax({
                    url: that.url,
                    dataType: 'json',
                    success: function (data) {
                        that.prepareTable(data, $jqxContainer, $eventListener);
                    },
                    error: function () {
                        console.log('Oops ... You should never rely on AJAX call!');
                    }
                });
            });

            $eventListener.on('showJqxGrid', function () {
                $jqxContainer.removeClass('hidden');
            });
        },

        /**
         * prepare table using jqGrid
         *
         * Example:
         *  {
         *
         *  }
         *
         * @param data JSON data.
         * @param dataFields
         * @param columns
         * @param $jqxSelector
         * @param $eventEmitter
         */
        prepareTable: function (data, $jqxSelector, $eventEmitter) {


            var dataJSONStr = JSON.stringify(data.resultSet);
            var dataFields = data.dataFields;
            var columns = data.columns;
            var source =
            {
                datatype: "json",
                datafields: dataFields,
                localdata: dataJSONStr
            };
            var dataAdapter = new $.jqx.dataAdapter(source);

            $jqxSelector.jqxGrid(
            {
                width: 850,
                source: dataAdapter,
                columnsresize: true,
                columns: columns
            });

            // after jqx grid complete
            $eventEmitter.trigger('showJqxGrid');
        }

    };

    $(document).ready(window.App.Users.init());

})($, window, document);